from rest_framework import serializers
from .models import City, DataCenter, Host, HostStatistics


class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = '__all__'


class DataCenterSerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(source='city.name', read_only=True)

    class Meta:
        model = DataCenter
        fields = '__all__'
        extra_fields = ['city_name']


class HostSerializer(serializers.ModelSerializer):
    data_center_name = serializers.CharField(source='data_center.name', read_only=True)
    city_name = serializers.CharField(source='data_center.city.name', read_only=True)

    class Meta:
        model = Host
        fields = '__all__'
        extra_fields = ['data_center_name', 'city_name']
        read_only_fields = ['last_password_change', 'is_reachable', 'last_reachable_check']

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        # 不返回密码信息
        representation.pop('root_password', None)
        return representation


class HostStatisticsSerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(source='city.name', read_only=True)
    data_center_name = serializers.CharField(source='data_center.name', read_only=True)

    class Meta:
        model = HostStatistics
        fields = '__all__'
        extra_fields = ['city_name', 'data_center_name']